
import java.io.*;
import java.util.*;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.lucene.index.Term;



public class Query {
	
    String qstring;
    public List termlist;
    int iteration;
    int resultnum=10;
    String Yahooid="NZV4PVfV34F9XCApUVMXK.q_.xlEGRnBDtLtaSQ6iYQgDJhqpTTS3akop5KvIU2THg--";
    
	public Query(String s)
	{
		qstring = s;
		iteration=0;
		pstring(qstring);
	}
	
	public Query(Term[] tm,int it)
	{
		qstring="";
		for(int i=0; i<tm.length; i++)
		{
			Term t = tm[i];
			qstring+=t.text()+" ";
		}
		qstring=qstring.trim();
		iteration=it;
		pstring(qstring);
		
	}
	
	public void pstring(String s)
	{
		StringTokenizer st = new StringTokenizer(s);
		termlist=new ArrayList();
		while(st.hasMoreTokens())
		{
			termlist.add(st.nextToken());
		}
	}
	
	public Presult runquery()
	{
		String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
	    HttpClient client = new HttpClient();

	    PostMethod method = new PostMethod(request);
	    try{FileOutputStream oos=new FileOutputStream("Transcript.txt",true);
        System.out.println("Try query: ( "+qstring+" )");
        oos.write(("Try query: ( "+qstring+" ) \n").getBytes());
	    }catch(Exception e){}
	    method.addParameter("appid", Yahooid);
	    method.addParameter("query", qstring);
	    method.addParameter("results", ""+resultnum);

	    try {
	    	int statusCode = client.executeMethod(method);
	        if (statusCode != HttpStatus.SC_OK) {
	        	System.err.println("Method failed: " + method.getStatusLine());
	        	return null;
	        }
	    } catch (IOException e) {
	    	System.err.println(e.getLocalizedMessage());
	    	return null;
	    }

	    InputStream rstream = null;
	    
	    try {
	    	rstream = method.getResponseBodyAsStream();
	    } catch (IOException e) {
	    	System.err.println(e.getLocalizedMessage());
	    	return null;
	    }

	    try {
	    	return new Presult(rstream);
	    } catch (Exception e) {
	    	System.err.println("cannot create results");
	    	return null;
	    }
	}
	
	public List getList()
	{
		return termlist;
	}
	public int getRound()
	{
		return iteration;
	}
}
